//
//  UserAccount.swift
//  MQWeibo
//
//  Created by SYN on 15/11/15.
//  Copyright © 2015年 SYN. All rights reserved.
//

import UIKit

import Alamofire

class UserAccount: NSObject , NSCoding{
    
    /// 用于调用access_token，接口获取授权后的access token。
    var access_token : String
    /// access_token的生命周期，单位是秒数。
    var expires_in : NSTimeInterval
    
    var expireDate : NSDate
    /// 当前授权用户的UID
    var uid : String
    /// 以下两个属性无法在初始化时获得
    /// 友好显示名称
    var name : String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large : String?

    //类的实例化
    init (dict: [String : AnyObject]){
        
        access_token = dict ["access_token"] as! String
        
        expires_in = dict ["expires_in"] as! NSTimeInterval
        
        expireDate = NSDate(timeIntervalSinceNow: expires_in)
        
        uid = dict ["uid"] as! String
        
    }
    //在swift中,如果函数要访问某一个属性值,需要使用到static
    //归档路径 - Document 可以 iTunes 备份,由应用程序产生的重要程序
    static let accountPath = ( NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString ).stringByAppendingPathComponent("account.plist")
    
    /**
    加载AccessToken
    */
    class func loadAccessToken(params: [String:String] , completion :(account: UserAccount? , error:NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        Alamofire.request(.POST, urlString, parameters: params).responseJSON(){ (JSON) in
            
            //如果出现错误,直接回调返回
            if JSON.result.error != nil || JSON.result.value == nil {
                completion(account: nil, error: JSON.result.error)
                
                return
            }
            
            //JSON有可能是字典有可能是数组
//            print(JSON)
            //字典转模型
            let account = UserAccount(dict: JSON.result.value as! [String:AnyObject])
            
//            print("account" , account)
            
            //加载用户信息 - uid 包含在 account 中
            account.loadUserInfo(completion)
            
            //键值保存归档数据
//            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccount.accountPath)
//            
//            //回调
//            completion(account: account, error: nil)
            
//            print(NSHomeDirectory())
            
            }.responseString() { (JSONString) in
                
//                print("JSONString" , JSONString)
                
        }
    }
    /// 加载用户信息
    func loadUserInfo(completion :(account: UserAccount? , error:NSError?) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["access_token":access_token,"uid":uid]
        
        Alamofire.request(.GET, urlString, parameters: params).responseJSON { (JSON) -> Void in
            
//            print(JSON)
            
            //错误处理
            if JSON.result.error != nil || JSON.result.value == nil {
                
                completion(account: nil, error: JSON.result.error)
                
                return
            }
            
            //给对象设置属性
            if let dict = JSON.result.value as? [String:AnyObject]{
                self.name = dict["name"] as? String
                
                self.avatar_large = dict["avatar_large"] as? String
                
//                print(self)
                //目前为止用户信息才是完整的
                //键值保存归档数据
                NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
                //回调
                completion(account: self, error: nil)
            } else {
                //可能性非常低 - 能够执行到此,网络回调 error == nil
                //提示:以下定义错误的方式与OC中是一致的
                let jsonError = NSError(domain: "MQWeibo", code: -10, userInfo: ["error": "数据解析错误"])
                
                completion(account: nil, error: jsonError)
                
            }
            
        }
    }
    
    
    /// 从本地沙盒读取用户数据(解档)
    // ***在什么地方调用 - appdelegate 中调用
    class func loadUserAccount() -> UserAccount? {
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount{
            //考虑一些细节 - 过期日期,一旦过期,需要重新登录
            //过期日期比当前日期大,所以比较结果是降序
            if account.expireDate.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        
        return nil
        
    }
    
    //重写数据信息描述 - 建议重要的数据模型类,添加一个,方便调试
    override var description:String{
        
        let properties = ["access_token","expires_in","expireDate","uid","name","avatar_large"]
        
//        print("description",dictionaryWithValuesForKeys(properties).description)
        
        return "\(dictionaryWithValuesForKeys(properties).description)"
        
    }
    
    /**
    *  归档&解档
    */
    
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        
        aCoder.encodeObject(expireDate, forKey: "expireDate")
        
        aCoder.encodeObject(uid, forKey: "uid")
        
        aCoder.encodeObject(name, forKey: "name")
        
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
        
        expireDate = aDecoder.decodeObjectForKey("expireDate") as! NSDate
        
        uid = aDecoder.decodeObjectForKey("uid") as! String
        
        name = aDecoder.decodeObjectForKey("name") as? String
        
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
}
